package platform.user.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import platform.user.api.UserServiceInterface;
import platform.user.auth.token.SessionToken;
import platform.user.auth.token.TokenGenerator;
import platform.user.auth.token.store.TokenStore;
import platform.user.model.LoginRequest;
import platform.user.model.LoginResponse;
import platform.user.model.User;
import platform.user.repository.UserRepository;

import javax.annotation.Nonnull;
import java.util.Collection;

/**
 * 用户 业务实现
 *
 * @author roamer
 * @version V1.0
 * @date 2019-03-10 10:20
 */
@Service
public class UserService implements UserServiceInterface {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenGenerator tokenGenerator;

    @Autowired
    private TokenStore tokenStore;

    @Override
    public User createUser(User user) {
        return userRepository.insert(user);
    }

    @Override
    public Collection<User> gerUsers() {
        return userRepository.findAll();
    }

    @Override
    public LoginResponse login(@Nonnull LoginRequest loginRequest) {
        User user = auth(loginRequest);
        LoginResponse loginResponse = new LoginResponse();
        if (user != null) {
            loginResponse.setUsername(user.getUsername());
            SessionToken sessionToken = tokenGenerator.createToken(user.getUsername());
            loginResponse.setToken(sessionToken.getValue());
            tokenStore.addToken(sessionToken);
        }
        return loginResponse;
    }

    /**
     * 认证
     *
     * @param loginRequest 登陆请求
     *
     * @return 用户信息
     */
    private User auth(LoginRequest loginRequest) {
        User user = userRepository.queryByUsername(loginRequest.getUsername());
        if (user != null && user.getPassword() != null && user.getPassword().equals(loginRequest.getPassword())) {
            return user;
        }
        return null;
    }
}
